package edu.ucsb.android.APMap;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.util.Log;

public class UdpSender implements Runnable{
	private static final int SERVERPORT = 1222;
	static byte [] SERVERADDR = new byte[] {(byte)169,(byte)254,(byte)87,(byte)205};
	byte[] buf;
	
	public UdpSender(byte[] content){
		buf = content;
	}
	
	public UdpSender(String content){
		buf = content.getBytes();
	}
	
	@Override
	public void run() {
		try {
			// Retrieve the ServerIP
			InetAddress serverAddr = InetAddress.getByAddress(SERVERADDR);
			
			Log.d("UDP", "C: Connecting...");
			/* Create new UDP-Socket */
			DatagramSocket socket = new DatagramSocket();
			Log.d("UDP","Socket created.");
			/*
			if (socket != null) {
				Log.d("UDP", "Didn't create socket");
			}*/
			
			
			/* Create UDP-packet with 
			 * data & destination(url+port) */
			DatagramPacket packet = new DatagramPacket(buf, buf.length,	serverAddr, SERVERPORT);
			Log.d("UDP", "C: Sending: '" + new String(buf) + "'");
			
			/* Send out the packet */
			socket.send(packet);
			Log.d("UDP", "C: Sent.");
			Log.d("UDP", "C: Done.");
		} catch (Exception e) {
			Log.e("UDP", "C: Error", e);
		}
	}
}
